from dataclasses import dataclass
from typing import Any

from speech_convert.models.response import Response


@dataclass
class PageResponse(Response):
    """分页数据响应模型

    继承基础响应类，包含分页信息和数据列表
    用于返回带分页功能的API响应
    """

    page: int = 1  # 当前页码
    page_size: int = 10  # 每页数据量
    page_total: int = 0  # 总页数
    data_total: int = 0  # 总数据量
    data: list[Any] | None = None  # 数据列表

    def __post_init__(self):
        # 确保数据列表不为空
        if self.data is None:
            self.data = []

        # 自动计算总页数
        if self.data_total > 0 and self.page_size > 0:
            self.page_total = (self.data_total + self.page_size - 1) // self.page_size
        else:
            self.page_total = 0

    def to_dict(self) -> dict[str, Any]:
        """转换为字典格式，便于序列化"""
        # 获取基类字段
        result = super().to_dict()

        # 添加分页字段
        result.update(
            {
                "page": self.page,
                "page_size": self.page_size,
                "page_total": self.page_total,
                "data_total": self.data_total,
                "data": self.data,
            }
        )

        return result

    @classmethod
    def from_dict(cls, data: dict[str, Any]) -> "PageResponse":
        """从字典创建 PageResponse 对象"""
        return cls(
            code=data.get("code", 200),
            message=data.get("message", "success"),
            page=data.get("page", 1),
            page_size=data.get("page_size", 10),
            page_total=data.get("page_total", 0),
            data_total=data.get("data_total", 0),
            data=data.get("data", []),
        )

    @classmethod
    def success(
        cls,
        data: list[Any],
        page: int = 1,
        page_size: int = 10,
        data_total: int = 0,
        message: str = "操作成功",
    ) -> "PageResponse":
        """创建成功的分页响应"""
        return cls(
            code=200,
            message=message,
            page=page,
            page_size=page_size,
            data_total=data_total or len(data),
            data=data,
        )

    @classmethod
    def error(cls, message: str, code: int = 500) -> "PageResponse":
        """创建错误的分页响应"""
        return cls(
            code=code, message=message, page=1, page_size=10, data_total=0, data=[]
        )
